package com.base.vistter.iframe.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.base.vistter.iframe.entity.InverterDevicesPowerMonth;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.mapper.InverterDevicesPowerMonthMapper;
import com.base.vistter.iframe.model.DevicesMonthPowerRequest;
import com.base.vistter.iframe.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class InverterDevicesPowerMonthService extends BaseService<InverterDevicesPowerMonthMapper, InverterDevicesPowerMonth> {

    @Transactional(readOnly = true)
    public List<InverterDevicesPowerMonth> statisticsDevices(DevicesMonthPowerRequest devicesMonthPowerRequest) {
        String column = Arrays.stream(devicesMonthPowerRequest.getColumns()).map(item -> "`" + item + "`").collect(Collectors.joining(","));
        Date startTime = DateUtils.getMonthStartTime(devicesMonthPowerRequest.getTime());
        Date endTime = DateUtils.getMonthEndTime(devicesMonthPowerRequest.getTime());
        List<InverterDevicesPowerMonth> list = this.baseMapper.statisticsDevicesMonth(column, devicesMonthPowerRequest.getDevicesId(), startTime, endTime);
        //如果是本月统计，则添加今日统计数据
//        if (DateUtils.isCurrentMonth(devicesMonthPowerRequest.getTime())) {
//           list.add(this.baseMapper.getTodayPower(column, devicesMonthPowerRequest.getDevicesId(), DateUtils.getTodayStartTime(), DateUtils.getTodayEndTime()));
//        }
        return list;
    }

    @Transactional(readOnly = true)
    public List<InverterDevicesPowerMonth> statisticsMonth(Integer stationId, Date time) {
        Date startTime = DateUtils.getMonthStartTime(time);
        Date endTime = DateUtils.getMonthEndTime(time);
        return this.baseMapper.statisticsMonth(stationId, startTime, endTime);
    }

    @Transactional(readOnly = true)
    public Long getDevicesPower(Integer devicesId, Date startTime ,Date endTime) throws IframeException{
        QueryWrapper<InverterDevicesPowerMonth> queryWrapper = Wrappers.query();
        queryWrapper.select("SUM(dp) as dp").eq("inverter_devices_id", devicesId).between("report_time", startTime, endTime);
        return super.selectOne(queryWrapper).getDP().longValue();
    }

}
